package com.tdcoding.chat.action.common;

import java.io.File;
import java.lang.reflect.InvocationTargetException;

import com.tdcoding.chat.constants.ChatConstants;
import com.tdcoding.chat.constants.MainConstants;
import com.tdcoding.chat.entities.ChatInfo;
import com.tdcoding.chat.entities.RequestInfo;
import com.tdcoding.chat.helper.FileHelper;
import com.tdcoding.chat.helper.Logger;
import com.tdcoding.chat.helper.StringHelper;
import com.tdcoding.chat.manager.ChatManager;

import io.netty.channel.Channel;

public class ActionRunnable implements Runnable {
	private RequestInfo requestInfo;
	private Channel channel;
	
	public ActionRunnable(Channel channel,RequestInfo requestInfo) {
		this.channel=channel;
		this.requestInfo=requestInfo;
	}
	
	public RequestInfo getRequestInfo() {
		return requestInfo;
	}

	public Channel getChannel() {
		return channel;
	}

	public void run() {
		Logger.println(this, "run");
		handleRunnable();
	}

	/**
	 * 处理消息
	 */
	private void handleRunnable() {
		String packetId=requestInfo.getPacketId();
		String method=requestInfo.getMethod();
		Logger.println(this, "handleRunnable",method);
		if (!StringHelper.hasValue(method)){
			ActionContext.writeResponse(channel,packetId, method,"The lack of necessary parameters.");
			return;
		}
		if (!method.equals(ChatConstants.REGISTER)
				&&!method.equals(ChatConstants.LOGIN)) {
			long userId=requestInfo.getUserId();
			if (userId<ChatConstants.CHAT_ADMINISTRATOR) {
				ActionContext.writeResponse(channel,packetId, method,"The lack of necessary parameters.");
				return;
			}
		}
		
		if (method.equals(ChatConstants.MSG_SEND)) {
			ChatInfo chatInfo=(ChatInfo) requestInfo.getParameters()[0];
			Logger.println(this, "handleRunnable~",chatInfo);
			if (chatInfo.getBodyType()==ChatConstants.CHAT_BODYTYPE_VOICE) {
				chatInfo=handleVoice(packetId,chatInfo);
				if (chatInfo==null) {
					ActionContext.writeResponse(channel,packetId, ChatConstants.MSG_RECEIPT,ChatConstants.MSG_SEND_FAILURE, "Not a valid voice file.");
					return;
				}
			}
			switch (chatInfo.getChatType()) {//0单聊；1群聊；2讨论组
//				case ChatConstants.CHAT_TYPE_SINGLE:
//					chattingToUser(packetId,chatInfo);
//					break;
//				default:
//					chattingToGroup(chatInfo);
//					break;
			}
		}
		else{
			ActionContext actionContext=ActionMapper.getInstance().getActionContext(method);
			Logger.println(this, "handleRunnable~~",actionContext);
			if (actionContext!=null) {
				try {
					actionContext.getMethod().invoke(actionContext.getBaseAction(), channel,requestInfo);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
					ActionContext.writeResponse(channel,packetId,method, e.getMessage());
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					ActionContext.writeResponse(channel, packetId,method,e.getMessage());
				} catch (InvocationTargetException e) {
					e.printStackTrace();
					ActionContext.writeResponse(channel,packetId,method, e.getMessage());
				}
			}
			else{
				ActionContext.writeResponse(channel,packetId,method, "There is no way for request.");
			}
		}
	}
	
	/**
	 * 是否已经登录
	 * @param userId
	 * @return	
	 */
	public boolean isLogined(long userId) {
		return ChatManager.existChannelInfo(userId);
	}

	/**
	 * 转发送信息（单聊）
	 * @param chatInfo
	 */
//	private void chattingToUser(String packetId,ChatInfo chatInfo){
//		ChannelInfo channelInfo=ChatManager.getChannelInfo(chatInfo.getChatToId());
//		Logger.println(this, "chattingToUser",chatInfo,channelInfo);
//		DBForChat.addChatInfo(ChatConstants.MSG_SEND_SENDING,chatInfo);
//		if (channelInfo!=null) {
//			Channel toChannel=channelInfo.getChatChannel();
//			if (toChannel!=null&&toChannel.isActive()
//					&&channelInfo.getStatus()==MainConstants.USER_STATUS_ONLINE) {//在线
//				Logger.println(this, "chattingToUser ","online");
//				ActionContext.handleResponse(toChannel,packetId,ChatConstants.MSG_RECEIVE,ChatConstants.MSG_SEND_SENDING,chatInfo);
//				return;
//			}
//		}
//		else{
//			ActionContext.writeResponse(this.channel,packetId,ChatConstants.MSG_RECEIPT,ChatConstants.MSG_SEND_RECEIPT,"");
//			MQManager.pushMsg(chatInfo);
//		}
//	}
//	
	/**
	 * 分发信息（群聊）
	 * @param chatInfo
	 */
//	private void chattingToGroup(ChatInfo chatInfo){
//		Logger.println(this, "chattingToGroup",chatInfo);
//		List<MemberInfo> lMemberInfos=DBForGroup.queryValidMembers(chatInfo.getChatToId());
//		List<ChannelInfo> lChannelInfos=ChatManager.getMemberChannelInfos(lMemberInfos);
//		for (ChannelInfo channelInfo : lChannelInfos) {
//			String respId=StringHelper.packetId();
//			chatInfo.setPacketId(respId);
//			chatInfo.setChatToRid(channelInfo.getUserId());
//			if (channelInfo.getUserId()==chatInfo.getChatId()) {
//				continue;
//			}
//			DBForChat.addChatInfo(ChatConstants.MSG_SEND_SENDING,chatInfo);
//			Channel toChannel=channelInfo.getChatChannel();
//			if (toChannel!=null&&toChannel.isActive()
//					&&channelInfo.getStatus()==MainConstants.USER_STATUS_ONLINE) {//在线
//				ActionContext.handleResponse(toChannel,respId,ChatConstants.MSG_RECEIVE,ChatConstants.MSG_SEND_SENDING, chatInfo);
//			}
//			else{
//				MQManager.pushMsg(chatInfo);
//			}
//		}
//	}
	
	private ChatInfo handleVoice(String packetId,ChatInfo chatInfo) {
		if (chatInfo.getChatContent()==null) {
			return null;
		}
		byte[] fileBytes=(byte[]) chatInfo.getChatContent();
		Logger.println(this, "handleVoice", fileBytes.length,chatInfo);
		File fileDir = new File(MainConstants.SERVER_FILE_PATH + File.separator+"audios");
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		File voiceFile = new File(fileDir, "voice_"+packetId+ ".amr");
		if (voiceFile.exists()) {
			voiceFile.delete();
		}
		boolean result=FileHelper.bytes2File(fileBytes, voiceFile);
		Logger.println(this, "handleVoice~", voiceFile.getName(),voiceFile.getAbsolutePath(),result);
		if (result) {
			chatInfo.setChatContent(MainConstants.SERVER_FILE_URL+"audios/"+voiceFile.getName());
			return chatInfo;
		}
		return null;
	}
	
}
